﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using seiacpscs_a2.datastructures.linkedlist;

namespace seiacpscs_a2.datastructures.hashtable
{
    public class HashTable: DataStructure
    {
        int size;

        int numberOfBuckets;
        public LinkedList[] buckets;

        HashTableStrategy strategy;

        private void initialize()
        {
            for (int i = 0; i < numberOfBuckets; i++)
            {
                buckets[i] = new LinkedList();
            }
        }

        private void build(int[] items)
        {

            for (int i = 0; i < items.Length; i++)
            {
                this.add(items[i]);
            }
        }

        public HashTable(int[] items, HashTableStrategy strategy)
        {

            this.strategy = strategy;
            this.numberOfBuckets = this.strategy.calculateNumberOfBuckets(items);
            this.buckets = new LinkedList[this.numberOfBuckets];
            this.initialize();
            this.build(items);
        }

        public override void add(int item)
        {

            int hashIndex = this.strategy.hash(item);
            LinkedList bucket = buckets[hashIndex];


            if (!bucket.contains(item))
            {
                buckets[hashIndex].add(item);
                ++(this.size);
            }
        }


        public override bool contains(int item)
        {
            int hashIndex = this.strategy.hash(item);

            if (hashIndex >= this.numberOfBuckets)
            {
                this.numberOfAccesses = 0;
                return false;
            }

            LinkedList bucket = buckets[hashIndex];
            if (bucket.contains(item))
            {
                this.numberOfAccesses = bucket.NumberOfAccesses;
                return true;
            }
            this.numberOfAccesses = bucket.NumberOfAccesses;
            return false;
        }
     
        public override String DataStructureName
        {
            get { return "HashTable"; }
        }

        public LinkedList getBucket(int index)
        {
            return this.buckets[index];
        }


        public int Size
        {
            get { return size; }
        }

        public int NumberOfBuckets
        {
            get { return this.numberOfBuckets; }
        }

    }
}
